from flask import Flask, request, jsonify
import datetime
from datetime import datetime, timedelta
import deepseek
import requests
from openai import OpenAI
from pymongo import MongoClient

app = Flask(__name__)

client = OpenAI(api_key="sk-NzE4LTExNTAwNjU4MTgxLTE3NDI1MTcyOTg3NzI=", base_url="https://api.scnet.cn/api/llm/v1")


mongo_client = MongoClient('mongodb://localhost:27017/')

# 定义数据库和集合
machine_id_db = mongo_client['machine_id_db']
machine_id_collection = machine_id_db['machine_id']

data_db = mongo_client['data_db']
data_collection = data_db['data']

error_db = mongo_client['error_db']
error_collection = error_db['error']

calorie_db = mongo_client['calorie_db']
calorie_collection = calorie_db['calorie']

distance_db = mongo_client['distance_db']
distance_collection = distance_db['distance']

#使用凯撒密码解密文本
def caesar_cipher_decrypt(text, shift=3):
    """使用凯撒密码解密文本"""
    decrypted_text = ""
    for char in text:
        if char.isalpha():
            shift_base = 65 if char.isupper() else 97
            decrypted_text += chr((ord(char) - shift_base - shift) % 26 + shift_base)
        else:
            decrypted_text += char
    return decrypted_text

#1.注册机器码(已实现)
@app.route('/register', methods=['POST'])
def register_machine():
    # 获取数据包
    data = request.json.get('data')
    if not data or not isinstance(data, dict):
        return jsonify({"code": "-1", "message": "Invalid or missing data"}), 400

    try:
        machine_id = data.get('machine_id')  # 注意拼写是否正确
        time_str = data.get('time')
        check_sum = int(data.get('check_sum'))
        
        # 检查必需字段是否存在
        if not all([machine_id, time_str, check_sum]):
            raise ValueError("Missing required fields")
    except Exception as e:
        return jsonify({"code": "-1", "message": f"Data parsing failed: {str(e)}"}), 400

    # 校验机器码是否已注册
    existing_machine = machine_id_collection.find_one({"machine_id": machine_id})
    if existing_machine:
        return jsonify({"code": "0", "message": "Machine_id has been registered"}), 400
    
    # 计算校验和并验证
    expected_check_sum = sum(ord(c) for c in f"{machine_id}{time_str}") % 100
    if check_sum != expected_check_sum:
        return jsonify({"code": "-3", "message": "Checksum verification failed"}), 400
    
    # 检查时间间隔
    upload_time = datetime.strptime(time_str, '%Y%m%d%H%M%S')
    if datetime.now() - upload_time > timedelta(hours=2):
        return jsonify({"code": "-4", "message": "Time expiration"}), 400
    
    # 写入数据库
    new_machine = {
        "machine_id": machine_id,
        "time": upload_time
    }
    try:
        machine_id_collection.insert_one(new_machine)
        return jsonify({"code": "0", "message": "Success"}), 201  # 添加这一行返回语句
    except Exception as e:
        return jsonify({"code": "-5", "message": f"Database write failed: {str(e)}"}), 500

# 2. 上传数据（已实现）
@app.route('/upload', methods=['POST'])
def upload_data():
    data = request.json.get('data')
    machine_id = request.json.get('machine_id')  # 直接从根对象获取machine_id
    
    if not data or not machine_id:
        return jsonify({"code": "-1", "message": "No machine_id"}), 400

    try:
        time_str = data.get('time')
        check_sum = int(data.get('check_sum'))
        
        # 检查必需字段是否存在
        if not all([time_str]):
            raise ValueError("Missing required fields")
    except Exception as e:
        return jsonify({"code": "-1", "message": f"No machine_id or missing required fields: {str(e)}"}), 400

    # 校验机器码是否已注册
    existing_machine = machine_id_collection.find_one({"machine_id": machine_id})
    if not existing_machine:
        return jsonify({"code": "-1", "message": "No machine_id"}), 400

    # 计算校验和并验证
    concatenated_str = (time_str +
                        data.get('heart_rate') +
                        data.get('breath_rate')+
                        data.get('body_temp') +
                        data.get('blood_pressure') +
                        data.get('step_count') +
                        data.get('distance') +
                        data.get('calories'))
    expected_check_sum = sum(ord(c) for c in concatenated_str) % 100
    print(f"Expected check_sum: {expected_check_sum}, Received check_sum: {check_sum}")  # Debug output
    if check_sum != expected_check_sum:
        return jsonify({"code": "-3", "message": "Data failed"}), 400

    # 检查时间间隔
    upload_time = datetime.strptime(time_str, '%Y%m%d%H%M%S')
    if datetime.now() - upload_time > timedelta(hours=2):
        return jsonify({"code": "-4", "message": "Time expiration"}), 400

    

    

    # 写入数据库
    new_data = {
        "pk_id": f"{machine_id}_{time_str}",
        "machine_id": machine_id,
        "time": upload_time,
        "heart_rate": int(data.get('heart_rate')),
        "breath_rate": int(data.get('breath_rate')),
        "body_temp": float(data.get('body_temp')),
        "blood_pressure": data.get('blood_pressure'),  # 字符串
        "steps": int(data.get('step_count')),
        "distance": float(data.get('distance')),
        "calories": float(data.get('calories'))
    }
    try:
        data_collection.insert_one(new_data)
    except Exception as e:
        return jsonify({"code": "-5", "message": "Write failed"}), 500

    return jsonify({"code": "0", "message": "Success"}), 201

# 3. 发送单次查询请求（已实现）
def get_registered_machines():
    try:
        machines = [machine['machine_id'] for machine in machine_id_collection.find({}, {"machine_id": 1, "_id": 0})]
        return machines
    except Exception as e:
        print(f"Error fetching machine IDs: {e}")
        return []

@app.route('/query', methods=['POST'])
def query_data():
    req_data = request.json
    print(f"Received request data: {req_data}")  # 调试信息

    # 获取请求参数
    data = req_data.get('data')
    if not data or 'query_time_start' not in data or 'query_time_end' not in data or 'time' not in data or 'machine_id' not in req_data:
        return jsonify({"code": "-1", "message": "Missing required fields"}), 400

    query_time_start_str = data.get('query_time_start')
    query_time_end_str = data.get('query_time_end')
    raw_time_str = data.get('time')
    time_str = raw_time_str.strip() if isinstance(raw_time_str, str) and raw_time_str is not None else None  # 安全地去除空格
    machine_id = req_data.get('machine_id')

    if not all([query_time_start_str, query_time_end_str, time_str, machine_id]):
        return jsonify({"code": "-1", "message": "Missing required field(s)"}), 400
    
    # 获取所有已注册的机器码
    registered_machines = get_registered_machines()

    # 判断机器码是否已经注册
    if machine_id not in registered_machines:
        return jsonify({"code": "-1", "message": "No machine_id"}), 400

    try:
        query_time_start = datetime.strptime(query_time_start_str, '%Y%m%d%H%M%S')
        query_time_end = datetime.strptime(query_time_end_str, '%Y%m%d%H%M%S')
        upload_time = datetime.strptime(time_str, '%Y%m%d%H%M%S')
        
        # 校验上传时间与当前时间间隔不超过2小时
        if datetime.now() - upload_time > timedelta(hours=2):
            return jsonify({"code": "-4", "message": "Time expiration"}), 400
        
        # 在数据库中查找数据（主键：machine_id+query_time）
        existing_data = list(data_collection.find({
            "machine_id": machine_id,
            "time": {"$gte": query_time_start, "$lte": query_time_end}
        }))
        if not existing_data:
            return jsonify({"code": "-5", "message": "No find data"}), 404

        response_data = []
        for data_item in existing_data:  # 改名为data_item避免与data变量冲突
            processed_data = {
                "machine_id": data_item["machine_id"],
                "time": data_item["time"].strftime('%Y%m%d%H%M%S'),
                # 添加其他需要的字段
            }
            # 或者如果你想要保留所有字段（除了_id）
            processed_data = {k: v.strftime('%Y%m%d%H%M%S') if isinstance(v, datetime) else v 
                            for k, v in data_item.items() if k != '_id'}
            response_data.append(processed_data)
            
        return jsonify({
            "code": "0",
            "message": "Success",
            "data": response_data
        }), 200

    except ValueError:
        return jsonify({"code": "-2", "message": "Invalid time format"}), 400
    except Exception as e:
        return jsonify({"code": "-3", "message": f"Unexpected error: {str(e)}"}), 400

# 4. 获取饮食建议（已实现）
def generate_diet_advice(data_features):
    """向AI发送用户数据并获取饮食建议"""
    response = client.chat.completions.create(
        model="DeepSeek-R1-Distill-Qwen-7B",
        messages=[
            {"role": "system", "content": "请直接输出饮食建议，不要分析解释。用'建议：'开头，保持简洁。示例格式：建议：1.每日500克蔬菜 2.每周3次深海鱼类 3.限制精制糖..."},
            {"role": "user", "content": f"用户数据：{data_features}"},
        ],
        stream=False,
    )
    if response.choices:
        advice = response.choices[0].message.content.strip()
        
        # 格式标准化处理
        if "建议：" not in advice:
            if "：" in advice:  # 处理全角冒号变异
                advice = advice.split("：", 1)[-1].strip()
                advice = "建议：" + advice
            else:  # 无前缀时自动补全
                advice = "建议：" + advice
        else:
            advice = "建议：" + advice.split("建议：", 1)[-1].strip()
            
        return advice
    raise Exception("AI服务无响应")

@app.route('/dietAdvice', methods=['POST'])
def get_diet_advice():
    req_data = request.json
    time_str = req_data.get('time')
    machine_id = req_data.get('machine_id')

    if not all([time_str, machine_id]):
        return jsonify({"code": "-1", "message": "Missing required fields"}), 400

    try:
        # 检查机器ID是否存在
        if not machine_id_collection.find_one({"machine_id": machine_id}):
            return jsonify({"code": "-1", "message": "No machine_id"}), 400

        upload_time = datetime.strptime(time_str, '%Y%m%d%H%M%S')
        if datetime.now() - upload_time > timedelta(hours=2):
            return jsonify({"code": "-2", "message": "Time expiration"}), 400

        # 修改为查询最近7天数据
        query_time_start = upload_time - timedelta(days=7)
        query_time_end = upload_time
        
        past_data = list(data_collection.find({
            "machine_id": machine_id,
            "time": {"$gte": query_time_start, "$lte": query_time_end}
        }))

        if not past_data:
            return jsonify({"code": "-5", "message": "No relevant data found in last 7 days"}), 404

        # 准备特征数据 - 添加周统计信息
        weekly_stats = {
            "avg_heart_rate": 0,
            "avg_breath_rate": 0,
            "total_steps": 0,
            "total_distance": 0,
            "total_calories": 0,
            "records_count": len(past_data)
        }

        valid_records = []
        for data in past_data:
            features = {
                "heart_rate": data.get("heart_rate"),
                "breath_rate": data.get("breath_rate"),
                "body_temp": data.get("body_temp"),
                "blood_pressure": data.get("blood_pressure"),
                "steps": data.get("steps", 0),
                "distance": data.get("distance", 0),
                "calories": data.get("calories", 0)
            }
            
            # 累计周统计
            if features["heart_rate"]: weekly_stats["avg_heart_rate"] += features["heart_rate"]
            if features["breath_rate"]: weekly_stats["avg_breath_rate"] += features["breath_rate"]
            weekly_stats["total_steps"] += features["steps"]
            weekly_stats["total_distance"] += features["distance"]
            weekly_stats["total_calories"] += features["calories"]
            
            valid_records.append(features)

        # 计算平均值
        if weekly_stats["records_count"] > 0:
            weekly_stats["avg_heart_rate"] = round(weekly_stats["avg_heart_rate"] / weekly_stats["records_count"], 1)
            weekly_stats["avg_breath_rate"] = round(weekly_stats["avg_breath_rate"] / weekly_stats["records_count"], 1)

        # 准备AI输入数据
        ai_input = {
            "weekly_stats": weekly_stats,
            "daily_records": valid_records
        }

        # 获取建议
        diet_advice = generate_diet_advice(ai_input)

        return jsonify({
            "code": "0",
            "message": "Success",
            "advice": diet_advice,
            "stats": weekly_stats  # 可选：返回统计信息给客户端
        }), 200

    except ValueError as e:
        app.logger.error(f"Value error: {str(e)}")
        return jsonify({"code": "-2", "message": "Invalid time format"}), 400
    except Exception as e:
        app.logger.error(f"Error in diet advice: {str(e)}", exc_info=True)
        return jsonify({"code": "-3", "message": "Internal server error"}), 500

# 5. 获取运动建议（已实现）
def generate_exercise_advice(data_features):
    """向AI发送用户数据并获取运动建议"""
    response = client.chat.completions.create(
        model="DeepSeek-R1-Distill-Qwen-7B",
        messages=[
            {"role": "system", "content": "请直接输出运动建议，不要分析解释。用'建议：'开头，保持简洁。示例格式：建议：1.每日慢跑30分钟 2.每周3次力量训练..."},
            {"role": "user", "content": f"用户数据：{data_features}"},
        ],
        stream=False,
    )
    if response.choices:
        advice = response.choices[0].message.content.strip()
        
        # 确保只保留建议部分
        if "建议：" in advice:
            advice = advice.split("建议：", 1)[-1].strip()  # 移除前缀
            advice = "建议：" + advice  # 保持格式统一
        return advice
    raise Exception("AI服务无响应")

@app.route('/exerciseAdvice', methods=['POST'])
def get_exercise_advice():
    req_data = request.json
    time_str = req_data.get('time')
    machine_id = req_data.get('machine_id')

    if not all([time_str, machine_id]):
        return jsonify({"code": "-1", "message": "Missing required fields"}), 400

    try:
        # 检查机器ID是否存在
        if not machine_id_collection.find_one({"machine_id": machine_id}):
            return jsonify({"code": "-1", "message": "No machine_id"}), 400

        upload_time = datetime.strptime(time_str, '%Y%m%d%H%M%S')
        if datetime.now() - upload_time > timedelta(hours=2):
            return jsonify({"code": "-2", "message": "Time expiration"}), 400

        # 查询最近7天数据
        query_time_start = upload_time - timedelta(days=7)
        query_time_end = upload_time
        
        past_data = list(data_collection.find({
            "machine_id": machine_id,
            "time": {"$gte": query_time_start, "$lte": query_time_end}
        }))

        if not past_data:
            return jsonify({"code": "-5", "message": "No relevant data found in last 7 days"}), 404

        # 准备运动相关统计数据
        exercise_stats = {
            "avg_heart_rate": 0,
            "total_active_minutes": 0,
            "total_steps": 0,
            "total_distance": 0,
            "total_calories_burned": 0,
            "active_days": 0,
            "records_count": len(past_data)
        }

        active_days = set()  # 记录有运动的天数
        for data in past_data:
            # 转换时间为日期格式
            record_date = data["time"].date()
            
            if data.get("heart_rate"): 
                exercise_stats["avg_heart_rate"] += data["heart_rate"]
            
            exercise_stats["total_steps"] += data.get("steps", 0)
            exercise_stats["total_distance"] += data.get("distance", 0)
            exercise_stats["total_calories_burned"] += data.get("calories", 0)
            
            # 如果有运动量则计入活跃日
            if data.get("steps", 0) > 3000 or data.get("distance", 0) > 2:  # 假设步数>3000或距离>2km算活跃
                active_days.add(record_date)
                exercise_stats["total_active_minutes"] += data.get("active_minutes", 30)  # 默认30分钟

        exercise_stats["active_days"] = len(active_days)
        if exercise_stats["records_count"] > 0:
            exercise_stats["avg_heart_rate"] = round(exercise_stats["avg_heart_rate"] / exercise_stats["records_count"], 1)

        # 准备AI输入数据
        ai_input = {
            "exercise_stats": exercise_stats,
            "activity_trend": {
                "most_active_day": max(active_days) if active_days else None,
                "least_active_day": min(active_days) if active_days else None
            }
        }

        # 获取运动建议
        exercise_advice = generate_exercise_advice(ai_input)

        return jsonify({
            "code": "0",
            "message": "Success",
            "advice": exercise_advice,
            "stats": exercise_stats  # 可选：返回统计信息
        }), 200

    except ValueError:
        return jsonify({"code": "-2", "message": "Invalid time format"}), 400
    except Exception as e:
        app.logger.error(f"Exercise advice error: {str(e)}", exc_info=True)
        return jsonify({"code": "-3", "message": "Internal server error"}), 500

# 6. 上传设备错误信息（已实现）
def is_machine_registered(machine_id):
    """
    检查指定的机器码是否已注册
    :param machine_id: 待检查的机器码
    :return: 如果已注册返回 True，否则返回 False
    """
    result = machine_id_collection.find_one({"machine_id": machine_id})
    return result is not None

@app.route('/errorReport', methods=['POST'])
def report_error():

    payload = request.json
    data = payload.get('data')
    machine_id = payload.get('machine_id')

    if not is_machine_registered(machine_id):
        return jsonify({"code": "-1", "message": "No machine_id"}), 400

    upload_time_str = data.get('time')
    try:
        upload_time = datetime.strptime(upload_time_str, '%Y%m%d%H%M%S')
    except ValueError:
        return jsonify({"code": "-2", "message": "Time format error"}), 400

    current_time = datetime.now()
    if current_time - upload_time > timedelta(hours=2):
        return jsonify({"code": "-2", "message": "Time expiration"}), 400

    error_message = data.get('error')
    if not error_message:
        return jsonify({"code": "-3", "message": "Error message is required"}), 400

    # 生成 pk_id
    pk_id = f"{machine_id}{upload_time_str}"

    new_error = {
        "pk_id": pk_id,
        "machine_id": machine_id,
        "time": upload_time,
        "error": error_message
    }
    try:
        error_collection.insert_one(new_error)
    except Exception as e:
        return jsonify({"code": "-3", "message": "Write failed"}), 500

    return jsonify({"code": "0", "message": "Success"}), 201

# 7. 设置卡路里目标(已实现)
@app.route('/setCalorieGoal', methods=['POST'])
def upload_calories():
    req_data = request.json
    
    # 获取machine_id和data对象
    machine_id = req_data.get('machine_id')
    data = req_data.get('data')
    
    # 验证必要字段是否存在
    if not all(key in data for key in ('time', 'calorie_target')) or machine_id is None:
        return jsonify({"code": "-1", "message": "Missing required fields"}), 400

    # 检查机器ID是否已注册
    if not machine_id_collection.find_one({"machine_id": machine_id}):
        return jsonify({"code": "-1", "message": "No machine_id"}), 400

    try:
        # 创建新的Calorie记录
        new_calorie = {
            "pk_id": f"{machine_id}_{data['time']}",
            "machine_id": machine_id,
            "time": datetime.strptime(data['time'], '%Y%m%d%H%M%S'),
            "calorie_target": int(data['calorie_target'])  # 统一使用小写字段名
        }
        
        # 使用update_one实现upsert，避免重复插入
        calorie_collection.update_one(
            {"pk_id": new_calorie["pk_id"]},
            {"$set": new_calorie},
            upsert=True
        )
        
        return jsonify({
            "code": "0",
            "message": "Calorie target set successfully!"
        }), 201
        
    except ValueError:
        return jsonify({"code": "-2", "message": "Invalid time format"}), 400
    except Exception as e:
        return jsonify({"code": "-3", "message": str(e)}), 500
        
# 8. 设置运动距离目标（已实现）
@app.route('/setDistanceGoal', methods=['POST'])
def upload_distance():
    req_data = request.json
    
    machine_id = req_data.get('machine_id')
    data = req_data.get('data')
    
    # 验证必要字段是否存在
    if not all(key in data for key in ('time', 'distance_target')) or machine_id is None:
        return jsonify({"code": "-1", "message": "Missing required fields"}), 400

    # 检查机器ID是否已注册
    if not machine_id_collection.find_one({"machine_id": machine_id}):
        return jsonify({"code": "-1", "message": "No machine_id"}), 400

    try:
        # 创建新的Distance记录
        new_distance = {
            "pk_id": f"{machine_id}_{data['time']}",
            "machine_id": machine_id,
            "time": datetime.strptime(data['time'], '%Y%m%d%H%M%S'),
            "distance_target": int(data['distance_target'])
        }
        
        # 使用update_one实现upsert
        distance_collection.update_one(
            {"pk_id": new_distance["pk_id"]},
            {"$set": new_distance},
            upsert=True
        )
        
        return jsonify({
            "code": "0",
            "message": "Distance target set successfully!"
        }), 201
        
    except ValueError:
        return jsonify({"code": "-2", "message": "Invalid time format"}), 400
    except Exception as e:
        return jsonify({"code": "-3", "message": str(e)}), 500

# 9. 获取剩余运动距离(已实现)
@app.route('/getRemainingDistance', methods=['POST'])
def get_remaining_distance():
    req_data = request.json
    machine_id = req_data.get('machine_id')
    upload_time_str = req_data.get('time')
    
    # 验证必要字段
    if not machine_id or not upload_time_str:
        return jsonify({"code": "-1", "message": "Missing required fields"}), 400
    
    # 检查机器ID是否已注册
    if not machine_id_collection.find_one({"machine_id": machine_id}):
        return jsonify({"code": "-1", "message": "No machine_id"}), 400
    
    try:
        upload_time = datetime.strptime(upload_time_str, '%Y%m%d%H%M%S')
        
        # 检查时间有效性
        if datetime.now() - upload_time > timedelta(hours=2):
            return jsonify({"code": "-2", "message": "Time expiration"}), 400
        
        # 获取最新的距离目标
        last_distance_record = distance_collection.find_one(
            {"machine_id": machine_id},
            sort=[("time", -1)]
        )
        
        if not last_distance_record:
            return jsonify({"code": "-3", "message": "No distance target set"}), 400
            
        start_time = last_distance_record["time"]
        distance_target = float(last_distance_record["distance_target"])
        
        # 计算累计距离
        pipeline = [
            {"$match": {
                "machine_id": machine_id,
                "time": {"$gte": start_time}
            }},
            {"$group": {
                "_id": None,
                "total_distance": {"$sum": "$distance"}
            }}
        ]
        
        result = list(data_collection.aggregate(pipeline))
        total_distance = result[0]["total_distance"] if result else 0.0
        
        remaining_distance = distance_target - total_distance
        
        if remaining_distance <= 0:
            return jsonify({
                "code": "1", 
                "message": "Success", 
                "data": {"remaining_distance": 0, "status": "target_achieved"}
            })
        else:
            return jsonify({
                "code": "0",
                "message": "Success",
                "data": {
                    "remaining_distance": round(remaining_distance, 2),
                    "target_distance": distance_target,
                    "progress": round((total_distance/distance_target)*100, 1)
                }
            })
            
    except ValueError:
        return jsonify({"code": "-2", "message": "Invalid time format"}), 400
    except Exception as e:
        return jsonify({"code": "-3", "message": str(e)}), 500


# 10. 获取剩余卡路里值（已实现）
@app.route('/getRemainingCalories', methods=['POST'])
def get_remaining_calories():
    req_data = request.json
    machine_id = req_data.get('machine_id')
    upload_time_str = req_data.get('time')
    
    # 验证必要字段
    if not machine_id or not upload_time_str:
        return jsonify({"code": "-1", "message": "Missing required fields"}), 400
    
    # 检查机器ID是否已注册
    if not machine_id_collection.find_one({"machine_id": machine_id}):
        return jsonify({"code": "-1", "message": "No machine_id"}), 400
    
    try:
        upload_time = datetime.strptime(upload_time_str, '%Y%m%d%H%M%S')
        
        # 检查时间有效性
        if datetime.now() - upload_time > timedelta(hours=2):
            return jsonify({"code": "-2", "message": "Time expiration"}), 400
        
        # 获取最新的卡路里目标
        last_calorie_record = calorie_collection.find_one(
            {"machine_id": machine_id},
            sort=[("time", -1)]
        )
        
        if not last_calorie_record:
            return jsonify({"code": "-3", "message": "No calorie target set"}), 400
            
        start_time = last_calorie_record["time"]
        calorie_target = float(last_calorie_record["calorie_target"])
        
        # 计算累计卡路里消耗
        pipeline = [
            {"$match": {
                "machine_id": machine_id,
                "time": {"$gte": start_time}
            }},
            {"$group": {
                "_id": None,
                "total_calories": {"$sum": "$calories"}
            }}
        ]
        
        result = list(data_collection.aggregate(pipeline))
        total_calories = result[0]["total_calories"] if result else 0.0
        
        remaining_calories = calorie_target - total_calories
        
        if remaining_calories <= 0:
            return jsonify({
                "code": "1", 
                "message": "Success", 
                "data": {"remaining_calories": 0, "status": "target_achieved"}
            })
        else:
            return jsonify({
                "code": "0",
                "message": "Success",
                "data": {
                    "remaining_calories": round(remaining_calories, 2),
                    "target_calories": calorie_target,
                    "progress": round((total_calories/calorie_target)*100, 1)
                }
            })
            
    except ValueError:
        return jsonify({"code": "-2", "message": "Invalid time format"}), 400
    except Exception as e:
        return jsonify({"code": "-3", "message": str(e)}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
